<?php
declare (strict_types = 1);
namespace app\shop\model;
use app\api\model\IdentityCard;
use app\common\job\ShopOrders;
use app\common\model\BaseModel;
use app\common\model\Config;
use app\common\self\MyJob;
use app\myself\Bc;
use app\order\model\Order;
use app\service\model\Service;
use app\shop\model\ShopWallet;
use think\Model;

use think\Db;

Class ShopUsers extends BaseModel
{
    public $error;


    // 视频-获取列表操作
    public function getList($get)
    {
        $type = isset($get['type']) ? $get['type'] : 0;
        $oredr = 'sort desc';
        $where = [
            ['status','=',1], // 状态1
            ['is_check','=',1], // 审核通过
            ['is_delete','=',0] // 存在的
        ];
        $whereOr = [];
        $is_hot = isset($get['is_hot']) ? $get['is_hot'] : -1;
        // 是否为首页视频 推荐视频
        if($is_hot >= 0 && !isset($get['title']) && $is_hot == 1)
            $where[] = ['is_hot','=',$is_hot];

        // 分类
        if($type && $type >= 1)
            $where[] = ['type_id','=',$type];
        // 搜索 title ,视频名称 和 用户昵称
        if(isset($get['title']) && $get['title'] && trim($get['title'])){
            $whereOr = [
                [['title','like',trim($get['title']).'%']],
                [['user_nick_name','like',trim($get['title']).'%']]
            ];
        }

        $field= 'id,title,cover,video,likes,shares,comments,add_time,uid,is_hot,position';
        $this->queryList($get,$field,$where,$oredr,$whereOr);
        foreach($this->modelList as $k => $v){
            $this->list['data'][$k]['user_nickname'] = isset($v->oneUser->nickname) ? $v->oneUser->nickname : '风再起时';
            $this->list['data'][$k]['user_avatarurl'] = isset($v->oneUser->avatarurl) ? getHostDominUrl($v->oneUser->avatarurl) : 'https://miaommeis-1301812909.cos.ap-guangzhou.myqcloud.com/icon/%E7%BC%96%E7%BB%84%205%402x.png';
//            if($this->list['data'][$k]['is_hot'] != $is_hot)
//                unset($this->list['data'][$k]);
        }
        $isRefresh = isset($get['isRefresh']) ? $get['isRefresh'] : 0;
        if($isRefresh && $isRefresh == 1) shuffle($this->list['data']);
    }


    /*
     * 申请创建店铺
     */
    public function createShop($user){
        try{
            if(empty($user)) exception('找不到该用户!');
            $data = Input('post.');
            if(empty($data['name'])||strlen($data['name']) < 2) exception('店铺名不能为空/店铺名过短!');
            if(empty($data['real_name'])) exception('真实姓名不能为空!');
            if(empty($data['phone'])) exception('手机号不能为空!');
            elseif(!preg_match("/^1[3456789]\d{9}$/", $data['phone'])) exception('请填写正确的手机号!');
            if(empty($data['identity'])) exception('身份证不能为空!');
            elseif(!IdentityCard::isValid($data['identity'])) exception('请填写正确的身份证!');
            if(empty($data['logo'])) exception('店铺logo不能为空!');
            if(empty($data['card_img_front'])) exception('身份证正面不能为空!');
            if(empty($data['card_img_back'])) exception('身份证反面不能为空!');
            if(empty($data['certificate_photo'])) exception('证件照不能为空!');
            if(empty($data['desc'])) exception('店铺描述不能为空!');
            if(empty($data['id']) && $this::where('name',trim($data['name']))->count()) exception('当前店铺名称已存在，麻烦更换一个!');
            if(empty($data['id']) && $this->where(['uid'=>$user->id,'is_delete'=>0])->count()) exception('您已经申请过店铺了，请勿重复申请!');
            /*$shopCount = $this->alias('u')->join('shop_user_info i','i.shop_id=u.id','left')->where(['i.identity'=>$data['identity'],'u.is_delete'=>0])->field('u.id')->select();
            if(!empty($shopCount)){
                $limit = (new Config())->toData('shopOrderConfig');
                if(count($shopCount) >= $limit['shop_limit']) exception('您的名下店铺过多，无法继续申请!');
            }*/

            $main = [
                'uid'=>$user->id,
                'name'=>emojiEncode($data['name']),
                'real_name'=>$data['real_name'],
                'phone'=>$data['phone'],
                'logo'=>$data['logo'],
                'add_time'=>time(),
            ];
            $info = [
                'identity'=>$data['identity'],
                'card_img'=>json_encode([
                    $data['card_img_front'],$data['card_img_back']
                ]),
                'certificate_photo'=>$data['certificate_photo'],
                'desc'=>$data['desc'],
                'rule'=>'',
            ];
            if($this::where(['uid'=>$user->id,'apply_status'=>0,'is_delete'=>0])->count()) exception('当前店铺正在审核中!');
            $shopUserInfoModel = new ShopUserInfo();
            if(!empty($data['id'])){
                $shopinfos = $this::where(['uid'=>$user->id,'is_delete'=>0])->find();
                if(!empty($shopinfos)&&!in_array($shopinfos['apply_status'],[0,2])) exception('当前店铺无法重新提交审核!');
                $main['apply_status'] = 0;
                $is_update = $this->where(['id'=>$data['id']])->update($main);
                $shopUserInfoModel->where(['shop_id'=>$data['id']])->update($info);
                return true;
            }elseif($last_id = $this->insertGetId($main)){
                $info['shop_id'] = $last_id;
                $shopUserInfoModel->insertGetId($info);
                /*
                // logo上传
                $pre_fix = app()->getRootPath().'/public';
                $linshiarrs = explode('/',$data['logo']);
                $linshi_str = '/newUploads/shop/user/logo/'.date('Y_m_d').$linshiarrs[count($linshiarrs)];
                $cos_url = 'https://admin-miaomeimei-1301812909.cos.ap-guangzhou.myqcloud.com'.$linshi_str;
                $queue_data = [
                    'file' => $pre_fix.$data['logo'],
                    'cos_path' => $linshi_str,
                    'id' => $last_id,
                    'table' => serialize($this),
                    'data' => [
                        'logo' => $cos_url
                    ]
                ];
                MyJob::pushQueue('FileUploadsJob',$queue_data,2);
                // 身份证信息正面上传
                $pre_fix = app()->getRootPath().'/public';
                $linshiarrs = explode('/',$data['card_img_front']);
                $linshi_str = '/newUploads/shop/user/card_img_front/'.date('Y_m_d').$linshiarrs[count($linshiarrs)];
                $cos_url_1 = 'https://admin-miaomeimei-1301812909.cos.ap-guangzhou.myqcloud.com'.$linshi_str;
                $queue_data = [
                    'file' => $pre_fix.$data['card_img_front'],
                    'cos_path' => $linshi_str
                ];
                MyJob::pushQueue('FileUploadsJob',$queue_data,2);
                // 身份证反面上传
                $pre_fix = app()->getRootPath().'/public';
                $linshiarrs = explode('/',$data['card_img_back']);
                $linshi_str = '/newUploads/shop/user/card_img_back/'.date('Y_m_d').$linshiarrs[count($linshiarrs)];
                $cos_url = 'https://admin-miaomeimei-1301812909.cos.ap-guangzhou.myqcloud.com'.$linshi_str;
                $queue_data = [
                    'file' => $pre_fix.$data['card_img_back'],
                    'cos_path' => $linshi_str,
                    'id' => $last_id,
                    'table' => serialize($shopUserInfoModel),
                    'data' => [
                        'card_img'=>json_encode([$cos_url_1,$cos_url]),
                    ]
                ];
                MyJob::pushQueue('FileUploadsJob',$queue_data,2);
                */
                return true;
            }
            exception('店铺申请失败，请稍后再试!');
            return false;
        }catch (\Exception $e){
            /*if(stristr($e->getMessage(),'SQLSTATE')){
                $this->error = '数据走丢了，请稍后再试！';
            }else*/ $this->error = $e->getMessage();
            return false;
        }
    }


    /*
     * 获取重新申请时数据
     */
    public function getReapplyInfo($user){
        try{
            if(empty($user)) exception('找不到该用户!');
            $shopUser = $this->alias('s')->join('shop_user_info i','s.id=i.shop_id','left')->where(['s.uid'=>$user->id,'s.is_delete'=>0])->find();
            if(!empty($shopUser)){
                $shopUser = $shopUser->toArray();
                if(!empty($shopUser['card_img'])){
                    if(is_array($shopUser['card_img'])) $img = json_decode($shopUser['card_img'],true);
                    else $img = explode(',',$shopUser['card_img']);
                }else $img = [];
                $shopUser['card_img'] = $img;
                return $shopUser;
            }
            exception('店铺信息不存在!');
            return false;
        }catch (\Exception $e){
            /*if(stristr($e->getMessage(),'SQLSTATE')){
                $this->error = '数据走丢了，请稍后再试！';
            }else*/ $this->error = $e->getMessage();
            return false;
        }
    }

    /**
     * 根据用户id 验证店铺状态是否ok 
     */
    public function regShop($uid){
        $shopUser = $this::where([
            'is_delete' => 0,
            'uid' => $uid
        ])->find();
        $list = ['msg'=>'店铺信息ok','flag'=> true];
        if(!$shopUser){
            $list['msg'] = '店铺不存在';
            $list['flag'] = false;
            return $list;
        }
        if($shopUser->is_open != 1){
            $list['msg'] = '店铺已关闭';
            $list['flag'] = false;
            return $list;
        };
        if($shopUser->apply_status != 1){
            $list['msg'] = '店铺没通过审核';
            $list['flag'] = false;
            return $list;
        }
        $list['data'] = $shopUser;
        return $list;
    }

    /**
     * 获取到店铺信息
     */
    public function infoShop($user){
        // 拿取店铺信息
        $shopModel = new  ShopUsers();
        $shopList = $shopModel->regShop($user->id);
        if(!$shopList['flag']) return retu_json(400,$shopList['msg']);
        $shopUser = $shopList['data'];

        // 今日时间戳
        $time1 = strtotime(date('Y-m-d 00:00:00',time()));
        //本月时间戳
        $timeMonth = mktime(0,0,0,date('m') - 0,1,date('Y') - 0);
        // 今日交易额
        $toDayWhere = [
            ['shop_id','=',$shopUser->id],
            ['add_time','>',$time1]
        ];
        $bc = new Bc();
        // 今日成交金额
        $toDayMoney = ShopOrderLog::where($toDayWhere)->sum('money');
        // 今日成交笔数
        $toDayLimit = ShopOrderLog::where($toDayWhere)->count();
        // 本月订单笔
        $monthLimit = ShopOrderLog::where([
            ['shop_id','=',$shopUser->id],
            ['add_time','>',$timeMonth]
        ])->count();
        // 待发货笔数
        $shipLimit = Order::where(['shop_id'=>$shopUser->id,'status' => 2])->count();
        // 待售后笔数
        /*
        $afterSaleLimit =  Service::where([
            ['shop_id','=',$shopUser->id],
            ['status','<>',5]])->count();
        */
        $afterSaleLimit = ShopOrderLog::where([
            ['shop_id','=',$shopUser->id],
            ['retuen_status','>',0]
        ])->count();
        return [
            'name' => $shopUser['name'],
            'logo' => $shopUser['logo'],
            'security_deposit' => $shopUser->getWalletOne ? $shopUser->getWalletOne->security_deposit : 0,
            'toDayMoney' => $bc->calcSub($toDayMoney,0,2),
            'toDayLimit' =>  $toDayLimit,
            'monthLimit' => $monthLimit,
            'shipLimit' => $shipLimit, 
            'afterSaleLimit' => $afterSaleLimit
        ];
    }

    /**
     * 获取到店铺钱包
     */
    public function getWalletOne(){
        return $this::hasOne(ShopWallet::class,'shop_id','id');
    }

    /**
     * 检查是否存在店铺
     */
    public function checkShop($id){
        $data = ['online'=>['apply_status'=>0,'describe'=>''],'offline'=>['apply_status'=>0,'describe'=>'']];
        $is_check = $this::where([['uid','=',$id],['is_delete','=',0]])->count();
        if($is_check > 0){
            $info = $this->alias('s')->join('shop_user_info i','s.id=i.shop_id','left')->where([['s.uid','=',$id],['s.type','=',1],['s.is_delete','=',0]])->field('s.id,s.apply_status,i.refuse_str')->find();
            if(!empty($info)){
                $data['online'] = $info;
                $data['online']['apply_status'] = ($info['apply_status'] == 2) ? -1 : $info['apply_status']+1;
                $data['online']['describe'] = ($info['apply_status'] == 2) ? ($info['refuse_str']??'店铺审核不通过！') : '';
            }
            $info = $this->alias('s')->join('shop_user_info i','s.id=i.shop_id','left')->where([['s.uid','=',$id],['s.type','=',2],['s.is_delete','=',0]])->field('s.apply_status,i.refuse_str')->find();
            if(!empty($info)){
                $data['offline']['apply_status'] = ($info['apply_status'] == 2) ? -1 : $info['apply_status']+1;
                $data['offline']['describe'] = ($info['apply_status'] == 2) ? ($info['refuse_str']??'店铺审核不通过！') : '';
            }
        }
        return $data;
    }

    /**
     * 获取店铺营收数据 
     */
    public function getRevenueData(&$user,$params){
        // 拿取店铺信息
        $shopModel = new  ShopUsers();
        $shopList = $shopModel->regShop($user->id);
        if(!$shopList['flag']) return retu_json(400,$shopList['msg']);
        $shopOne = $shopList['data'];

        // 店铺可以提现的金额
        $shopWalletOne = ShopWallet::where('shop_id',$shopOne->id)->field('money')->find();
        // 开始日期
        $day = isset($params['time']) ? strtotime($params['time']) : strtotime(date('Y-m',time()));
        // 结束时间戳
        $end =  strtotime(date('Y-m',$day)." +1 month");
        $where = [];
        $where[] = ['shop_id','=',$shopOne->id];
        $where[] = ['add_time','>=',$day];
        $where[] = ['add_time','<',$end];
        // 本月订单
        $monthOrderNum =  ShopOrderLog::where($where)->count();
        // 订单总数
        $orderNum = ShopOrderLog::where('shop_id',$shopOne->id)->count();
        // 本月售后
        $monthServiceNum =  ShopOrderLog::where(array_merge($where,[['retuen_status','>',0]]))->count();
        // 本月成交元  排除掉 退款的售后订单  
        $monthDealOrderNum = ShopOrderLog::where(array_merge($where,[['retuen_status','<',2]]))->sum('money');
        // 总成交金额
        $sumMoney = ShopOrderLog::where([
            ['shop_id','=',$shopOne->id],
            ['retuen_status','<',2]
        ])->sum('money');
        // 待确认收款 - 元
        $preOrderNum = ShopOrderLog::where([
            ['shop_id','=',$shopOne->id],
            ['status','=',0]
        ])->sum('money');
        $bc = new Bc();
        return [
            'money' => $shopWalletOne->money, // 可提现余额
            'monthOrderNum' => $monthOrderNum, // 本月订单
            'orderNum' => $orderNum, // 订单总数
            'monthServiceNum' => $monthServiceNum, // 本月售后
            'monthDealOrderNum' => $bc->calcDiv($monthDealOrderNum,1,2), // 本月成交 元
            'sumMoney' =>  $bc->calcDiv($sumMoney,1,2), // 总成交金额 元
            'preOrderNum' => $bc->calcDiv($preOrderNum,1,2), // 待确认收款 元
        ];
    }
}
